package com.jsjosem.aftersales.ui.worktickets;

import static com.jsjosem.aftersales.utils.CommonUtils.getDepartmentsMenu;
import static com.jsjosem.aftersales.utils.CommonUtils.getProvincesCity;
import static com.jsjosem.aftersales.utils.CommonUtils.selectTime;
import static com.jsjosem.aftersales.utils.CommonUtils.setSpinnerAdapter;
import static com.zx.sdk.api.ZXManager.TAG;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.jsjosem.aftersales.R;
import com.jsjosem.aftersales.api.CustomerApi;
import com.jsjosem.aftersales.api.DepartmentsApi;
import com.jsjosem.aftersales.api.RetrofitClient;
import com.jsjosem.aftersales.data.request.CustomerRequest;
import com.jsjosem.aftersales.data.response.BaseResponse;
import com.jsjosem.aftersales.data.response.CityResponse;
import com.jsjosem.aftersales.data.response.DepartmentsResponse;
import com.jsjosem.aftersales.data.response.DepartmentsUserResponse;
import com.jsjosem.aftersales.data.response.PageResponse;
import com.jsjosem.aftersales.request.AsyncRequest;
import com.jsjosem.aftersales.utils.ImmUtils;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Retrofit;

public class CreateCustomerActivity extends AppCompatActivity {

    private ConstraintLayout createCustomerLayout;
    private ImageView icBack;
    private EditText customerIdET, customerNameET, customerAddressET, customerDetailsAddressET, customerDirectorET, customerDateInfoET, customerShortNameET;
    private Spinner customerTypeSp, industrySp, customerPropertiesSp, serviceNetworkSp, customerLabelSp, customerGradeSp, customerSourceSp;
    private View customerAddressView, customerDirectorView, customerDateView;
    private Button commit;
    private final CityResponse province = new CityResponse();
    private final CityResponse city = new CityResponse();
    private final CityResponse county = new CityResponse();
    private final DepartmentsUserResponse resDepartmentsUserResponse = new DepartmentsUserResponse();
    private final List<DepartmentsResponse> deptList = new ArrayList<>();
    private String customerType, industry, customerProperties, customerLabel, customerGrade, customerSource;
    private DepartmentsResponse serviceNetwork;
    private final String[] customerTypeList = {
            "客户",
            "供应商",
            "分销商",
            "合作伙伴",
            "公共媒体",
            "银行",
            "中介",
            "外部资源",
            "竞争对手",
            "个人用户"
    };

    private final String[] industryList = {
            "新能源",
            "汽车",
            "智能制造",
            "化工",
            "医疗"
    };

    private final String[] customerPropertiesList = {
            "国企",
            "民企",
            "外资",
            "合资"
    };

    private final String[] customerLabelList = {
            "重要",
            "一般",
            "核心",
            "VIP"
    };

    private final String[] customerGradeList = {
            "A",
            "B",
            "C",
    };

    private final String[] customerSourceList = {
            "企业开拓",
            "主动联系",
            "客户推荐",
            "企业人脉"
    };

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_customer);
        initView();
        initData();

        // 设置EditText的hint字体大小
        ImmUtils.setCloseKeyboard(createCustomerLayout, this);
        ImmUtils.setEditTextHintFontSize(customerIdET, 14, "客户编号将在创建后由系统生成");
        ImmUtils.setEditTextHintFontSize(customerAddressET, 14, "请选择区域");
        ImmUtils.setEditTextHintFontSize(customerDetailsAddressET, 14, "请填写详细地址");
        ImmUtils.setEditTextHintFontSize(customerDirectorET, 14, "请选择");
        ImmUtils.setEditTextHintFontSize(customerDateInfoET, 14, "请选择");

        setSpinnerAdapter(this, customerTypeSp, customerTypeList, 0);
        setSpinnerAdapter(this, industrySp, industryList, 0);
        setSpinnerAdapter(this, customerPropertiesSp, customerPropertiesList, 0);
        setSpinnerAdapter(this, customerLabelSp, customerLabelList, 0);
        setSpinnerAdapter(this, customerGradeSp, customerGradeList, 0);
        setSpinnerAdapter(this, customerSourceSp, customerSourceList, 0);
        setSpListener();

        customerAddressView.setOnClickListener(v -> {
            getProvincesCity(CreateCustomerActivity.this, customerAddressET, province, city, county);
        });

        customerDirectorView.setOnClickListener(v -> {
            getDepartmentsMenu(this, customerDirectorET, resDepartmentsUserResponse);
        });

        customerDateView.setOnClickListener(view -> {
            selectTime(this, customerDateInfoET);
        });

        commit.setOnClickListener(v -> {
            CustomerRequest customerRequest = new CustomerRequest();
            if (customerNameET.getText().toString().isEmpty()) {
                showToast("客户名称不能为空");
                return;
            } else {
                customerRequest.setName(customerNameET.getText().toString());
            }
            if (customerAddressET.getText().toString().isEmpty()) {
                showToast("客户地址不能为空");
                return;
            } else {
                customerRequest.setProvinceId(Long.valueOf(province.getCitycode()));
                customerRequest.setCityId(Long.valueOf(city.getCitycode()));
                customerRequest.setCountyId(Long.valueOf(county.getCitycode()));
            }
            if (customerDetailsAddressET.getText().toString().isEmpty()) {
                showToast("客户详细地址不能为空");
                return;
            } else {
                customerRequest.setAddress(customerDetailsAddressET.getText().toString());
            }
            if (customerDirectorET.getText().toString().isEmpty()) {
                showToast("客户负责人不能为空");
                return;
            } else {
                customerRequest.setOwnerId(resDepartmentsUserResponse.getId());
            }
            if (customerDateInfoET.getText().toString().isEmpty()) {
                showToast("签约时间不能为空");
                return;
            } else {
                customerRequest.setContactAt(customerDateInfoET.getText().toString());
            }
            if (!customerShortNameET.getText().toString().isEmpty()) {
                customerRequest.setShortName(customerShortNameET.getText().toString());
            }
            customerRequest.setEntryTypeName(customerType);
            customerRequest.setIndustryName(industry);
            customerRequest.setCustomerTypeName(customerProperties);
            customerRequest.setDepartmentId(serviceNetwork.getId().toString());
            customerRequest.setTagName(customerLabel);
            customerRequest.setSafeLevel(customerGrade);
            customerRequest.setSource(customerSource);
            createCustomer(customerRequest);

        });

        icBack.setOnClickListener(v -> {
            finish();
        });
    }


    private void initView() {
        icBack = findViewById(R.id.create_customer_img_back);
        customerNameET = findViewById(R.id.customer_name);
        customerIdET = findViewById(R.id.customer_id);
        customerAddressET = findViewById(R.id.customer_address);
        customerDetailsAddressET = findViewById(R.id.customer_details_address);
        customerDirectorET = findViewById(R.id.customer_director);
        customerDateInfoET = findViewById(R.id.customer_date_info);
        createCustomerLayout = findViewById(R.id.create_customer_lay);
        customerAddressView = findViewById(R.id.customer_address_view);
        customerDirectorView = findViewById(R.id.customer_director_view);
        customerDateView = findViewById(R.id.customer_date_view);
        customerTypeSp = findViewById(R.id.customer_type_spinner);
        customerPropertiesSp = findViewById(R.id.customer_properties_spinner);
        serviceNetworkSp = findViewById(R.id.service_network_spinner);
        customerLabelSp = findViewById(R.id.customer_label_spinner);
        customerGradeSp = findViewById(R.id.customer_grade_spinner);
        customerSourceSp = findViewById(R.id.customer_source_spinner);
        industrySp = findViewById(R.id.industry_spinner);
        commit = findViewById(R.id.bt_commit);
        customerShortNameET = findViewById(R.id.customer_short_name);
    }

    private void initData() {
        getDept();
    }

    private void getDept() {
        Retrofit mRetrofit = RetrofitClient.getInstance();
        DepartmentsApi departmentsApi = mRetrofit.create(DepartmentsApi.class);
        Call<PageResponse<DepartmentsResponse>> getDepartments = departmentsApi.getDepartments();
        AsyncRequest<PageResponse<DepartmentsResponse>> request = new AsyncRequest<>();
        request.sendRequest(getDepartments, res -> {
            deptList.addAll(res.getData());
            //把deptList转换成String数组
            String[] deptNameList = new String[deptList.size()];
            for (int i = 0; i < deptList.size(); i++) {
                deptNameList[i] = deptList.get(i).getName();
            }
            setSpinnerAdapter(this, serviceNetworkSp, deptNameList, 0);
        }, err -> {
            Log.e(TAG, "getDept: " + err.toString());
        });
    }

    private void setSpListener() {
        customerTypeSp.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                customerType = customerTypeList[i];
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        industrySp.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                industry = industryList[i];
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        customerPropertiesSp.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                customerProperties = customerPropertiesList[i];
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        serviceNetworkSp.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                serviceNetwork = deptList.get(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        customerLabelSp.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                customerLabel = customerLabelList[i];
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        customerGradeSp.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                customerGrade = customerGradeList[i];
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        customerSourceSp.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                customerSource = customerSourceList[i];
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    private void createCustomer(CustomerRequest customerRequest){
        Retrofit mRetrofit = RetrofitClient.getInstance();
        CustomerApi customerApi = mRetrofit.create(CustomerApi.class);
        Call<BaseResponse<Void>> createCustomer = customerApi.createCustomer(customerRequest);
        AsyncRequest<BaseResponse<Void>> request = new AsyncRequest<>();
        request.sendRequest(createCustomer, res -> {
            showToast("创建成功");
            finish();
        }, err -> {
            Log.e(TAG, "createCustomer: " + err.toString());
        });
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}